import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

//store状态管理库
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    id: '',
    shopName: "",
    logo: "",
    avatar: "https://msn-img-nos.yiyouliao.com/inforec-20220506-1a0f9b020da10f8ee99b875f3c4c24d3.png?time=1651999362&signature=04B0353D555E2651B74688EF6332FBC7"
  }
}

const state = getDefaultState()

// vuex方法
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // 设置name
  SET_NAME: (state, name) => {
    state.name = name
  },
  //设置id
  SET_ID: (state, id) => {
    state.id = id
  },
  // 设置地址
  SET_ADDRESS: (state, address) => {
    state.address = address
  },
  // 设置店名
  SET_SHOPNAME: (state, shopName) => {
    state.shopName = shopName;
  },
  // 设置logo
  SET_LOGO: (state, logo) => {
    state.logo = logo
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: username.trim(), pw: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          return reject('获取登录信息失败')
        }
        //解构返回用户信息
        const { account, address, shopname, _id } = data
        console.log(data)
        // 设置名字
        commit('SET_NAME', account)
        // 设置id
        commit('SET_ID', _id)
        // 设置地址
        commit('SET_ADDRESS', address)
        // 设置店名
        commit('SET_SHOPNAME', shopname)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 退出登录
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken()
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

